using System;
using System.Collections.Generic;
using System.Linq;
using ApiProject.Api.Data;
using ApiProject.Api.Entity;
using ApiProject.Api.PramaModel;
using ApiProject.Api.Repository;
using ApiProject.Api.Uitls;
using ApiProject.Api.Utils;
using Microsoft.AspNetCore.Authorization;
using Microsoft.AspNetCore.Hosting;
using Microsoft.AspNetCore.Mvc;
using Microsoft.EntityFrameworkCore;
using Microsoft.Extensions.Configuration;
using Newtonsoft.Json;

//商品
namespace ApiProject.Api.Controllers
{
    // [Authorize]
    [ApiController]
    [Route("[controller]")]
    public class OrdersController : ControllerBase
    {
        private IRepository<Orders> _orderRepository;
        private IRepository<OrderInfo> _orderInfoRepository;
        private IRepository<Commodities> _commoditiesRepository;
        private IRepository<CommodityDetails> _commoditydetailsRepository;
        private IRepository<ShoppingCar> _carRepository;


        public OrdersController(
            IRepository<Orders> orderRepository,
            IRepository<OrderInfo> orderInfoRepository,
             IRepository<Commodities> commoditiesRepository,
             IRepository<CommodityDetails> commoditydetailsRepository,
             IRepository<ShoppingCar> carRepository
        )
        {
            _orderRepository = orderRepository;
            _orderInfoRepository = orderInfoRepository;
            _commoditiesRepository = commoditiesRepository;
            _commoditydetailsRepository = commoditydetailsRepository;
            _carRepository = carRepository;
        }


        //管理员查找所有的订单信息
        //Get /orders
        [HttpGet]
        public dynamic GetAllOrder()
        {

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = "order",
                Msg = "查找成功"
            });
        }


        // 用户添加订单
        // Post /orders
        [HttpPost]
        public dynamic AddOrder(NewOrder model)
        {
            var selectCommodity = model.SelectCommodity;
            var receivingId = model.ReceivingId;
            var paymentId = model.PaymentId;

            Random ran = new Random();
            var orderNumber = DateTime.Now.ToString("yyMMddHHmmss") + ran.Next(1000, 9999).ToString();

            ComData jsondata = new ComData();
            foreach (var item in selectCommodity)
            {
                jsondata = JsonConvert.DeserializeObject<ComData>(item.ToString());
                Console.WriteLine(jsondata.commodityDetailId);


                //商品详情表 减库存
                var comDetails = _commoditydetailsRepository.Table.Where(x => x.Id == jsondata.commodityDetailId).FirstOrDefault();
                var comInventory = (comDetails.Inventory - jsondata.inventory);


                comDetails.Inventory = comInventory;
                comDetails.UpdateTime = DateTime.Now;
                _commoditydetailsRepository.Update(comDetails);


                // 购物车删除数据
                var car = _carRepository.Table.Where(x => x.Id == jsondata.carId).FirstOrDefault();
                car.IsDelete = true;
                car.UpdateTime = DateTime.Now;
                _carRepository.Update(car);


                var neworder = new Orders
                {
                    CommodityId = jsondata.commodityDetailId,
                    UserId = model.UserId
                };

                _orderRepository.Insert(neworder);

                var orderInfo = new OrderInfo
                {
                    OrderId = neworder.Id,
                    OrderNumber = orderNumber,
                    OrderPrice = jsondata.price,
                    Comnum = jsondata.inventory,
                    ReceivingId = receivingId,
                    PayTime = DateTime.Now
                };

                _orderInfoRepository.Insert(orderInfo);

            }

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = orderNumber,
                Msg = "添加成功"
            });

        }

        public class ComData
        {
            public int commodityDetailId { get; set; }
            public int carId { get; set; }
            public int inventory { get; set; }
            public string commodityName { get; set; }
            public int price { get; set; }
        }


        //确定付款
        //Post /orders/ispay
        [HttpPost, Route("isPay")]
        public dynamic AddPay(NewOrder model)
        {
            var orderInfo = _orderInfoRepository.Table.Where(x => x.OrderNumber == model.OrderNumber).ToList();

            foreach (var item in orderInfo)
            {
                item.IsPay = true;
                item.PayTime = DateTime.Now;

                _orderInfoRepository.Update(item);
            }

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = "",
                Msg = "付款成功"
            });
        }


        //查找该用户所有订单
        // Get /order/all/id
        [HttpGet, Route("all/{id}")]
        public dynamic GetAllOrderByUserId(int id)
        {
            var goods = from o in _orderRepository.Table
                        join g in _commoditydetailsRepository.Table on o.CommodityId equals g.Id
                        join n in _commoditiesRepository.Table on g.CommodityId equals n.Id
                        where o.UserId == id
                        select new { o.Id, n.CommodityName };

            var allOrder = from g in goods
                           join info in _orderInfoRepository.Table on g.Id equals info.OrderId
                           select new { g.CommodityName, info.OrderNumber, info.OrderPrice, info.Comnum, info.PayTime, info.IsPay, info.IsSend, info.IsTake };

            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = allOrder,
                Msg = "查找成功"
            });

        }


        // 添加购物车
        // Post /orders/car/userid
        [HttpPost, Route("car/{id}")]
        public dynamic AddCar(int id, NewOrder model)
        {

            var isDetails = _carRepository.Table.Where(x => x.CommodityDetailId == model.ComDetailId && x.UserId == id && x.IsDelete == false).FirstOrDefault();

            if (isDetails == null)
            {
                var newCar = new ShoppingCar
                {
                    CommodityDetailId = model.ComDetailId,
                    UserId = id,
                    CarComNum = model.CarComNum
                };

                _carRepository.Insert(newCar);
                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = "",
                    Msg = "添加购物车成功"
                });
            }else{

                isDetails.CarComNum += model.CarComNum;
                isDetails.UpdateTime = DateTime.Now;

                _carRepository.Update(isDetails);

                return JsonHelper.Serialize(new
                {
                    Code = 200,
                    Data = "",
                    Msg = "添加购物车成功"
                });

            }



        }


        //查找购物车
        // Get /orders/car/userid
        [HttpGet, Route("car/{id}")]
        public dynamic GetCar(int id)
        {

            var allcoms = from detail in _commoditydetailsRepository.Table
                          join car in _carRepository.Table on detail.Id equals car.CommodityDetailId
                          where car.UserId == id && car.IsDelete == false
                          select new
                          {
                              carId = car.Id,
                              commodityDetailId = detail.Id,
                              price = detail.Price,
                              inventory = car.CarComNum,
                              allinventory = detail.Inventory,
                              commodityId = detail.CommodityId
                          };

            var CarCommodityInfo = from comName in _commoditiesRepository.Table
                                   join comId in allcoms on comName.Id equals comId.commodityId
                                   select new
                                   {
                                       CommodityName = comName.CommodityName,
                                       CarId = comId.carId,
                                       CommodityDetailId = comId.commodityDetailId,
                                       Price = comId.price,
                                       Inventory = comId.inventory,
                                       Allinventory = comId.allinventory,
                                       CommodityId = comId.commodityId
                                   };


            return JsonHelper.Serialize(new
            {
                Code = 200,
                Data = CarCommodityInfo,
                Msg = "查找成功"
            });


        }











    }
}
